package com.wx.qrcode.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import com.wx.qrcode.common.constant.RedisConstant;
import com.wx.qrcode.common.constant.WxUrlConstant;
import com.wx.qrcode.common.dto.LoginInfoDTO;
import com.wx.qrcode.common.dto.TextMessage;
import com.wx.qrcode.common.dto.WxCreateQrCodeDTO;
import com.wx.qrcode.common.dto.WxCreateQrCodeResultDTO;
import com.wx.qrcode.common.redis.RedisService;
import com.wx.qrcode.wx.properties.WxProperties;
import com.wx.qrcode.wx.util.MessageUtil;
import com.wx.qrcode.wx.util.SHA1Util;
import com.wx.qrcode.wx.util.WxUtil;
import io.netty.util.Constant;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author yz
 * @description
 * @date 2022-03-24 10:26
 */
@RestController
@RequestMapping("/wx")
@RequiredArgsConstructor
@Slf4j
public class WxController {
    private final RedisService redisService;
    private final WxProperties wxProperties;

    @GetMapping("/createQrCode")
    public String createQrCode(String signature) {
        WxCreateQrCodeResultDTO qrCode = WxUtil.createQrCode(signature);
        LoginInfoDTO build = LoginInfoDTO.builder().ticket(qrCode.getTicket()).signature(signature).build();
        redisService.set(RedisConstant.TICKET + qrCode.getTicket(), build, WxCreateQrCodeDTO.EXPIRE_SECONDS);
        redisService.set(RedisConstant.SIGNATURE + signature, qrCode.getTicket(), WxCreateQrCodeDTO.EXPIRE_SECONDS);
        return StrUtil.format(WxUrlConstant.SHOW_QR_CODE, qrCode.getTicket());
    }

    @GetMapping("/whetherTheLogin")
    public Boolean whetherTheLogin(String signature) {
        Object o = redisService.get(RedisConstant.SIGNATURE + signature);
        if (Objects.isNull(o)){
            return false;
        }
        LoginInfoDTO build = (LoginInfoDTO) redisService.get(RedisConstant.TICKET + o);
        if (BeanUtil.isEmpty(build)){
            return false;
        }
        if (StrUtil.isBlank(build.getOpenId())){
            return false;
        }

        return true;
    }

    /**
     * 消息配置
     *
     * @param request
     * @param response
     */
    @SneakyThrows
    @GetMapping("/receiveMessages")
    public void getReceiveMessages(HttpServletRequest request, HttpServletResponse response) {
        log.info("推送请求");
        String sha1 = SHA1Util.getSHA1(wxProperties.getToken(), request.getParameter("timestamp"), request.getParameter("nonce"));
        if (!request.getParameter("signature").equals(sha1)) {
            log.warn("未知来源请求");
            return;
        }
        if (request.getParameter("echostr") != null) {
            response.getWriter().write(request.getParameter("echostr"));
            return;
        }
    }

    @SneakyThrows
    @PostMapping("/receiveMessages")
    public String postReceiveMessages(HttpServletRequest request, HttpServletResponse response) {
        // xml请求解析
        Map<String, String> requestMap = MessageUtil.parseXml(request);

        // 发送方帐号（open_id）
        String fromUserName = requestMap.get("FromUserName");
        // 公众帐号
        String toUserName = requestMap.get("ToUserName");
        // 消息类型
        String msgType = requestMap.get("MsgType");


        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(fromUserName);
        textMessage.setFromUserName(toUserName);
        textMessage.setCreateTime(System.currentTimeMillis());
        textMessage.setMsgType("text");
        textMessage.setFuncFlag(0);

        // 关注消息
        if (msgType.equals("event")&&(requestMap.get("Event").equals("SCAN")||requestMap.get("Event").equals("subscribe"))) {
            textMessage.setContent("登录成功");
            LoginInfoDTO build = (LoginInfoDTO) redisService.get(RedisConstant.TICKET + requestMap.get("Ticket"));
            build.setOpenId("FromUserName");
            redisService.set(RedisConstant.TICKET + requestMap.get("Ticket"), build, WxCreateQrCodeDTO.EXPIRE_SECONDS);
        }
        return MessageUtil.textMessageToXml(textMessage);

    }
}
